package com.cqut.forum.controller;


import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqut.forum.entity.Filestore;
import com.cqut.forum.entity.User;
import com.cqut.forum.entity.Userfile;
import com.cqut.forum.entity.Ztree;
import com.cqut.forum.service.IFileStoreService;
import com.cqut.forum.service.IUserFileService;
import com.cqut.forum.service.IUserService;

import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DESUtils;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.StringUtil;
@Controller
public class NetdiskController {
	Logger logger  =  Logger.getLogger(PostController_2. class );
	private IUserService userService;
	private IUserFileService userFileService;
	private IFileStoreService fileStoreService;
    public IUserService getUserService() {
		return userService;
	}
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public IUserFileService getUserFileService() {
		return userFileService;
	}
	public void setUserFileService(IUserFileService userFileService) {
		this.userFileService = userFileService;
	}
	public void setFileStoreService(IFileStoreService fileStoreService) {
		this.fileStoreService = fileStoreService;
	}
	/**
	* @Title: getnetdisk
	* @Description: 返回网络硬盘界面  
	* @return String  
	* @author 刘强   
	* @date 2015-5-15 上午10:20:45
	*/ 
	@RequestMapping(value="getnetdisk.do")
	public String getnetdisk(HttpServletRequest request,HttpServletResponse response){
		String levelStr=request.getParameter("parentLevel");
		String parentIdStr=request.getParameter("parentId");
		String fileTypeStr=request.getParameter("fileType");
		int level=0;
		int parentId=-1;
		int fileType=-1;
		if(null!=levelStr) level=Integer.parseInt(levelStr)+1;
		if(null!=parentIdStr) parentId=Integer.parseInt(parentIdStr);
		if(null!=fileTypeStr) fileType=Integer.parseInt(fileTypeStr);
		request.setAttribute("level", level);
		request.setAttribute("parentId", parentId);
		request.setAttribute("fileType", fileType);
    	return "/home/netdisk";
	}
	/**
	* @Title: getnetdiskJson
	* @Description: 返回网络硬盘数据  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 上午10:20:21
	*/ 
	@RequestMapping(value="getnetdiskJson.do")
    public void getnetdiskJson(HttpServletRequest request,HttpServletResponse response){
    	Map<String,Object> root=new HashMap<String,Object>();
    	String page=request.getParameter("page");
    	String fileType=request.getParameter("fileType");
    	String parentId=request.getParameter("parentId");
    	String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		User user=userService.getUserByEmail(DESUtils.decode(cookieName));
		int pageSize=Integer.parseInt(ConfigProperties.get("netdiskPageSize"));
		List<Userfile> lists=new ArrayList<Userfile>();
		int total=0;
		if(Integer.parseInt(fileType)!=-1){//如果filetype为-1，则表示没有文件类型限制
			lists=userFileService.getUserfileByUserIdAndfileType(user.getId(), Integer.parseInt(fileType), Integer.parseInt(page), pageSize);
			total=userFileService.getUserfileTotalByUserIdAndfileType(user.getId(), Integer.parseInt(fileType));
		}else{
			lists=userFileService.getUserfile(user.getId(), Long.parseLong(parentId), Integer.parseInt(page), pageSize);
			total=userFileService.getUserfileTotal(user.getId(),Long.parseLong(parentId));
		}
		for(Userfile userfile:lists){
			if(userfile.getIsFile()==1){
				Filestore filestore=fileStoreService.getFilestoreByMD5(userfile.getMd5());
				userfile.setFilestore(filestore);
			}
		}
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", lists);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

    }
	/**
	* @Title: newFile
	* @Description: 新建文件夹  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 上午10:21:57
	*/ 
	@RequestMapping(value="/newFile.do")
	public void newFile(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String parentLevel=request.getParameter("parentLevel");
		String parentId=request.getParameter("parentId");
		String fileName=request.getParameter("fileName");
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		User user=userService.getUserByEmail(DESUtils.decode(cookieName));
		Userfile userfile=new Userfile();
        userfile.setFileName(fileName);
        userfile.setUserId(user.getId());
        userfile.setIsFile(0);
        userfile.setLevel(Integer.parseInt(parentLevel) + 1);
        userfile.setParentId(Long.parseLong(parentId));
        userfile.setCreateDate(DateUtil.getCurrentTimestamp());
        userFileService.save(userfile);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: fileReName
	* @Description: 文件重命名  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 下午2:10:26
	*/ 
	@RequestMapping(value="/fileReName.do")
	public void fileReName(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String userfileId=request.getParameter("userfileId");
		String userfileName=request.getParameter("userfileName");
		Userfile userfile=userFileService.getUserfileById(Long.parseLong(userfileId));
		userfile.setFileName(userfileName);
		userFileService.update(userfile);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: deleteUserfile
	* @Description: 删除userfile  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 下午2:22:42
	*/ 
	@RequestMapping(value="/deleteUserfile.do")
	public void deleteUserfile(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String userfileId=request.getParameter("userfileId");
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		User user=userService.getUserByEmail(DESUtils.decode(cookieName));
		userFileService.deleteUserfile(Long.parseLong(userfileId));
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	
	/**
	* @Title: netdiskLoadFile
	* @Description: 文件下载  
	* @return void  
	* @author 刘强   
	 * @throws Exception 
	* @date 2015-5-15 下午5:04:40
	*/ 
	@RequestMapping(value="/netdiskLoadFile.do")
	public void netdiskLoadFile(HttpServletRequest request,HttpServletResponse response) {
		String userfileId=request.getParameter("userfileId");
		Userfile userfile=userFileService.getUserfileById(Long.parseLong(userfileId));
		String ctxPath = request.getSession().getServletContext().getRealPath(
				"/");
		File file=null;
		if(userfile.getIsFile()==1){
			Filestore filestore=fileStoreService.getFilestoreByMD5(userfile.getMd5());
			file=new File(ctxPath+"\\"+filestore.getFilepath().replace("/", File.separator));
		}else{
			try{
				file=new File(userfile.getFileName()+".zip");
				ZipOutputStream zipStream = null;
				zipStream = new ZipOutputStream(new FileOutputStream(file));
				handleFile(file, zipStream, userfile, "",ctxPath);
				zipStream.close();
			}catch (Exception e){
				logger.error("NerdiskController方法netdiskLoadFile",e);
			}
		}
		 //设置文件MIME类型  
        response.setContentType("application/OCTET-STREAM;charset=UTF-8");  
        //设置Content-Disposition
		try{
			if(userfile.getIsFile()==1){
				response.setHeader("Content-Disposition", "attachment;filename=" +java.net.URLEncoder.encode(userfile.getFileName(), "UTF-8") );
			}else{
				response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
			}
		}catch (Exception e){
			logger.error("NerdiskController方法netdiskLoadFile",e);
		}
        //读取目标文件，通过response将目标文件写到客户端  
        //读取文件  
        InputStream in;
		try {
			in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();  
			//写文件  
			int b;  
			while((b=in.read())!= -1)  
			{  
				out.write(b);  
			}  
			in.close();  
			out.close();  
		} catch (Exception e) {
			logger.error("NetdiskController方法netdiskLoadFile", e);
		}  

	}
	/**
	* @Title: getDirectoryJson
	* @Description: 个人网盘目录  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 下午7:12:39
	*/ 
	@RequestMapping(value="/getDirectoryJson.do")
	public void getDirectoryJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String cookieName=CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME);	
		User user=userService.getUserByEmail(DESUtils.decode(cookieName));
		List<Ztree> lists=userFileService.getUserfileByUserIdAndisFile(user.getId(), 0);
		root.put("result", 1);
		root.put("lists",lists);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: fileMove
	* @Description: 文件移动 
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 下午8:41:16
	*/ 
	@RequestMapping(value="/fileMove.do")
	public void fileMove(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String userfileId=request.getParameter("userfileId");
		String targetId=request.getParameter("targetId");
		Userfile userfile=userFileService.getUserfileById(Long.parseLong(userfileId));
		userfile.setParentId(Long.parseLong(targetId));
		userFileService.updateUserFile(userfile);
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	
	private byte[] buf=new byte[1024*4];
	/**
	* @Title: handleFile
	* @Description: 用递归将文件打包  
	* @return void  
	* @author 刘强   
	* @date 2015-5-15 下午5:53:09
	*/ 
	private void handleFile(File zipFile, ZipOutputStream zipOut,Userfile userfile,String dirName,String ctxPath){
		try {
			
		     if(userfile.getIsFile()==0){
		    	 Integer childNum=userFileService.getUserfileChildNum(userfile.getId());
		    	 if(childNum==0){
		    		 zipOut.putNextEntry(new ZipEntry(dirName+zipFile.getName()+File.separator));
		    		 zipOut.closeEntry();
		    	 }else{
		    		 List<Userfile> lists=userFileService.getUserfileByParentId(userfile.getId());
		    		 for(Userfile userf:lists){
		    			 File fi=null;
		    			 if(userf.getIsFile()==1){
		    				 Filestore filestore=fileStoreService.getFilestoreByMD5(userf.getMd5());
		    				 fi=new File(ctxPath+"\\"+filestore.getFilepath().replace("/", File.separator));
		    			 }else{
		    				 fi=new File(userf.getFileName());
		    			 }
		    			 handleFile(fi, zipOut, userf, dirName+zipFile.getName()+File.separator,ctxPath);
		    		 }
		    	 }
		     }else{
		    	 FileInputStream fileIn  = new FileInputStream(zipFile);
		            //放入一个ZipEntry
		            zipOut.putNextEntry(new ZipEntry(dirName+zipFile.getName()));
		            int length = 0;
		            //放入压缩文件的流  
		            while ((length = fileIn.read(buf)) > 0) {
		                zipOut.write(buf, 0, length);
		            }  
		            //关闭ZipEntry，完成一个文件的压缩
		            fileIn.close();
		            zipOut.closeEntry();
		     }
		} catch (IOException e) {
			logger.error("NerdiskController方法handleFile",e);
		}
	}
}
